#include "word.h"
#include <iostream>
#include <fstream>

WordCounter::WordCounter(char * s): myfile(s), mycount(0){}

WordCounter::~WordCounter(){}

int WordCounter::wordcount()
{
    size_t i = 0;
    while(myfile[i] != '.')
        ++i;
    if ((myfile[i + 1] == 't') && (myfile[i + 2] == 'x') && (myfile[i + 3] == 't'))
        return txtcounter();
    return xmlcounter();
}

int WordCounter::txtcounter()
{
    std::cout << "format - txt\n";
    std::ifstream content(myfile);
    char simb;
    content.get(simb);
    while (!content.eof())
    {
        std::string str;
        while (content.get(simb) && (simb != '\n'))
            str = str + simb;
        mycount = mycount + this->counter(str);
    }
    content.close();
    return mycount;
}
int WordCounter::xmlcounter()
{
    std::cout << "format - xml\n";
    std::ifstream content(myfile);
    char simb;
    while(content.get(simb))
    {
        switch (simb)
        {
            case '"':
            {
                std::string str;
                while ((content.get(simb)) && (simb != '"'))
                    str = str + simb;
                mycount = mycount + this->counter(str);
                break;
            }
            case '>':
            {
                std::string str;
                while ((content.get(simb)) && (simb != '<'))
                    str = str + simb;
                mycount = mycount + this->counter(str);
                break;
            }
            default:;
        }
    }
    content.close();
    return mycount;
}

int WordCounter::counter(std::string srt)
{
    char signs[8] = {'.', ',', '!', '?', ' ', ':', '-', '\n'};
    size_t i = 0;
    int count = 0;
    while (i<srt.length())
    {
        while ((i < srt.length()) && ((srt[i] == signs[0]) || (srt[i] == signs[1]) || (srt[i] == signs[2]) || (srt[i]== signs[3]) ||
                    (srt[i] == signs[4]) || (srt[i] == signs[5]) || (srt[i] == signs[6]) || (srt[i] == signs[7])))
                    ++i;
        if (i != srt.length())
            count++;
        while ((i < srt.length()) && ((srt[i] != signs[0]) && (srt[i] != signs[1]) && (srt[i] != signs[2]) && (srt[i]!= signs[3]) &&
                    (srt[i] != signs[4]) && (srt[i] != signs[5]) && (srt[i] != signs[6]) && (srt[i] != signs[7])))
                    ++i;
    }
    return count;
}

